package org.fuys.etp.core.metrics.impl.info;

import org.fuys.etp.core.metrics.EtpMetricsHandler;
import org.fuys.etp.core.model.vo.TpStatusVO;
import org.fuys.etp.core.pool.EtpThreadPoolExecutor;
import org.fuys.etp.core.reject.EtpRejectHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @projectName: fuys-etp-final
 * @package: org.fuys.etp.core.metrics.impl.info
 * @className: BaseInfoHandler
 * @author: WangJing
 * @description: 基本信息收集器
 * @date: 2025/2/18 22:29
 * @version: 1.0
 */
@Component
public class BaseInfoHandler implements EtpMetricsHandler {

    @Override
    public void metricsCollect(ThreadPoolExecutor executor, TpStatusVO result) {
        final int size = executor.getQueue().size();
        final int remainingCapacity = executor.getQueue().remainingCapacity();
        final int allSize = size + remainingCapacity;
        result.setQueueSize(allSize);
        result.setQueueUsage((double) (size) / (double) (allSize));
        result.setMaximumPoolSize(executor.getMaximumPoolSize());
        result.setCorePoolSize(executor.getCorePoolSize());
        result.setCurrentPoolSize(executor.getPoolSize());
        final RejectedExecutionHandler rejectedExecutionHandler = executor.getRejectedExecutionHandler();
        if(rejectedExecutionHandler instanceof EtpRejectHandler){
            result.setRejectCount(((EtpRejectHandler) rejectedExecutionHandler).rejectCount());
        }
        result.setSumTaskCount(executor.getTaskCount());
    }

}
